/*
 * Created by JFormDesigner on Tue Sep 14 09:05:11 CST 2021
 */

package com.minelx.woods.pc.form.dialog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.minelx.sqlstructures.common.Files;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Tinkle
 */
public class SelectPid extends JDialog {

    private List<String> resultPids;

    private final JSONObject proxiesAsJSON;

    public static void main(String[] args) {
        new SelectPid(null).setVisible(true);
    }

    public SelectPid(Window owner) {
        super(owner, "", ModalityType.APPLICATION_MODAL);
        initComponents();

        proxiesAsJSON = JSON.parseObject(Files.toString("/mappings/proxies.json"));

        tree1.setModel(showCity());

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (resultPids == null) {
                    JOptionPane.showMessageDialog(SelectPid.this, "未输入");
                    return;
                }
                // close the window
                SelectPid.this.dispose();
            }
        });
    }

    private TreeModel showCity() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
        //                node.add(new DefaultMutableTreeNode(child));
        assert proxiesAsJSON != null;
        proxiesAsJSON.getJSONArray("children").toJavaList(JSONObject.class).forEach(proxyAsJSON -> {
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(proxyAsJSON.getString("name"));
            proxyAsJSON.getJSONArray("children")
                    .toJavaList(JSONObject.class)
                    .stream()
                    .filter(children2 -> children2.getJSONArray("children") != null)
                    .forEach(children2 -> {
                        DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(children2.getString("name"));
                        node.add(node2);
                        children2.getJSONArray("children")
                                .toJavaList(JSONObject.class)
                                .stream()
                                .filter(children3 -> children3.getJSONArray("children") != null)
                                .forEach(children3 -> {
                                    DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(children3.getString("name"));
                                    node2.add(node3);
                                    children3.getJSONArray("children")
                                            .toJavaList(JSONObject.class)
                                            .stream()
                                            .map(children4 -> new DefaultMutableTreeNode(children4.getString("name")))
                                            .forEach(node3::add);
                                });
                    });
            root.add(node);
        });
        return new DefaultTreeModel(root);
    }

    private void tree1ValueChanged(TreeSelectionEvent e) {
        List<String> pidArr = Arrays.stream(e.getPath().getPath()).skip(1).map(String::valueOf).collect(Collectors.toList());
        if (pidArr.isEmpty()) {
            return;
        }
        JSONArray children = proxiesAsJSON.getJSONArray("children");
        resultPids = new ArrayList<>();
        List<JSONObject> jsonObjects = children.toJavaList(JSONObject.class);
        for (String city : pidArr) {
            for (JSONObject jsonObject : jsonObjects) {
                if (jsonObject.get("name").toString().equals(city)) {
                    resultPids.add(jsonObject.get("code").toString());
                    if (jsonObject.getJSONArray("children") != null) {
                        JSONArray children1 = jsonObject.getJSONArray("children");
                        jsonObjects = children1.toJavaList(JSONObject.class);
                    }
                    break;
                }
            }
        }

        System.out.println(resultPids);
        // TODO add your code here
    }

    public int[] getSelectedProxies() {
        return resultPids.stream().mapToInt(Integer::parseInt).toArray();
    }

    private void tree1ValueChanged() {
        // TODO add your code here
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		dialogPane = new JPanel();
		scrollPane1 = new JScrollPane();
		tree1 = new JTree();

		//======== this ========
		setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		var contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== dialogPane ========
		{
			dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
			dialogPane.setLayout(new BorderLayout());

			//======== scrollPane1 ========
			{

				//---- tree1 ----
				tree1.addTreeSelectionListener(e -> {
			tree1ValueChanged();
			tree1ValueChanged(e);
			tree1ValueChanged(e);
		});
				scrollPane1.setViewportView(tree1);
			}
			dialogPane.add(scrollPane1, BorderLayout.CENTER);
		}
		contentPane.add(dialogPane, BorderLayout.CENTER);
		setSize(560, 670);
		setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private JPanel dialogPane;
	private JScrollPane scrollPane1;
	private JTree tree1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
